#include<stdio.h>
#include<string.h>
#include<mysql/mysql.h>

#define HOST "127.0.0.1" //mysql服务器的地址
#define PORT 3306 //端口，端口默认就是3306
#define USER "root"//mysql默认情况下是不允许用户远程登录的，用公网地址是访问不了的
#define PASS "jth951230."
#define DBNAME "gobang"

int main()
{
    //1.初始化Mysql句柄
    //MYSQL *mysql =mysql_init(MYSQL *mysql)如果传空会自己在堆上申请空间，来初始化句柄，并返回首地址
    MYSQL *mysql =mysql_init(NULL);
    if(mysql==NULL)
    {
        printf("mysql init failed \n");
        return -1;
    }
    //2.连接服务器
    //MYSQL *mysql_real_connect(mysql, host, user, passwd,db, port, unix_socket, client_flag);
    if(mysql_real_connect(mysql,HOST,USER,PASS,DBNAME,PORT,NULL,0)==NULL)
    {
        //如果返回为空，连接服务器失败
        printf("connect mysql server failed : %s\n",mysql_error(mysql));
        mysql_close(mysql);//退出前把mysql这个句柄释放掉
        return -1;
    }

    //3.设置客户端字符集
    //int mysql_set_character_set(MYSQL *mysql, const char *csname)
    if(mysql_set_character_set(mysql,"utf8")!=0)
    {
        printf("set client character failed : %s\n",mysql_error(mysql));
        mysql_close(mysql);
        return -1;
    }

    //4.选择要操作的数据库
    //int mysql_select_db(mysql,dbname)
    //mysql_select_db(mysql,DBNAME)
    //已经默认选择过了，已经不需要额外再去写一遍
 
    //5.执行sql语句
    //int mysql_query(MYSQL *mysql, const char *stmt_str)
    //char *sql="insert stu values(null,'小明',18,53,89,56);";
    //char *sql="delete from stu where sn=1;";
    //char *sql="update stu set ch=ch+40 where sn=2;";
    char *sql="select * from stu;";
    int ret=mysql_query(mysql,sql);
    if(ret!=0)
    {
        printf("%s\n",sql);
        printf("mysql query failed : %s\n",mysql_errno(mysql));
        mysql_close(mysql);
        return -1;
    }

    //6.如果sql语句是查询语句，则需要保存结果到本地
    //MYSQL_RES *mysql_store_result(MYSQL *mysql)
    MYSQL_RES *res=mysql_store_result(mysql);//获取结果集
    if(res==NULL)
    {
        mysql_close(mysql);
        return -1;
    }

    //7.获取结果集的结果条数
    // int mysql_num_rows(MYSQL_RES *res);//获取行数
    // int mysql_num_fields(MYSQL_RES *res);//获取列数
    int num_row=mysql_num_rows(res);
    int num_col=mysql_num_fields(res);//从结果集里面获取行和列

    //8.遍历保存到本地的结果集
    for(int i=0;i<num_row;i++)
    {
        //MYSQL_ROW mysql_fetch_row(MYSQL *res);//遍历结果的接口
        MYSQL_ROW row=mysql_fetch_row(res);//先对行进行遍历
        for(int j=0;j<num_col;j++)
        {
            //结果集中的结果都是用字符串来存储的
            printf("%s\t",row[j]);
        }
        printf("\n");
    }   
    
    //9.释放结果集
    mysql_free_result(res);
    //10.关闭连接，释放句柄
    mysql_close(mysql);


    return 0;
}